<template>
  <BasicModal v-bind="$attrs" @register="register" @ok="handleSubmit" :title="getTitle">
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { fromConfig } from './formData';
  import { addeqtClassApi, editeqtClassApi } from '/@/api/sys/brand/brand';
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      method: { type: String, defaultValue: 'add' },
      formData: { type: Object },
    },
    emits: ['success'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm(fromConfig);
      const [register, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        data && onDataReceive(data);
      });
      function onDataReceive(data) {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue(data.rowdata);
        }
      }
      const getTitle = computed(() => (!unref(isUpdate) ? '新增设备分类' : '编辑设备分类'));
      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            await editeqtClassApi(values, {
              id: values.id,
            });
          } else {
            await addeqtClassApi(values);
          }
          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      return { register, getTitle, registerForm, handleSubmit };
    },
  });
</script>
